<#
.SYNOPSIS
    Wrapper to run a single Alpha-SQL task using evolutionary algorithm locally with logging.

.DESCRIPTION
    This script verifies required environment variables (`OPENAI_API_KEY`), then
    runs the Python helper `tools/run_one_task.py` with the provided config for evolutionary solver.
    Output is tee'd to a timestamped log file under `logs\`.

.EXAMPLE
    # set env first in PowerShell
    $env:OPENAI_BASE_URL='https://vip.yi-zhan.top/v1'
    $env:OPENAI_API_KEY='<YOUR_API_KEY>'
    .\tools\run_evolutionary_one_task.ps1 -Config 'config/qwen32b_bird_dev_evolutionary.yaml' -TaskId 0
#>

param(
    [string]$Config = "config/qwen32b_bird_dev_evolutionary.yaml",
    [int]$TaskId = 0
)

if (-not $env:OPENAI_API_KEY) {
    Write-Error "Environment variable OPENAI_API_KEY is not set. Please set it before running the script."
    exit 1
}

if (-not (Test-Path $Config)) {
    Write-Error "Config file not found: $Config"
    exit 1
}

# Ensure logs dir exists
$logsDir = Join-Path -Path (Get-Location) -ChildPath "logs"
New-Item -ItemType Directory -Path $logsDir -Force | Out-Null

$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$logFile = Join-Path $logsDir "run_evolutionary_one_task_$timestamp.log"

$argsList = @($Config)
if ($TaskId -gt 0) { $argsList += @("--task-id", $TaskId) }

Write-Output "Starting run_one_task.py with config=$Config task-id=$TaskId (evolutionary solver)"
Write-Output "Logging to: $logFile"

# Run the Python script and tee output to log
& python -m tools.run_one_task $argsList 2>&1 | Tee-Object -FilePath $logFile

if ($LASTEXITCODE -ne 0) {
    Write-Error "run_one_task.py exited with code $LASTEXITCODE. See log: $logFile"
    exit $LASTEXITCODE
}

Write-Output "Completed. See log: $logFile"
